import { getOrder } from "@/api/order";

const state = {
  orderList: [],
};

const mutations = {
  SET_ORDER_LIST(state, list) {
    state.orderList = list;
    localStorage.setItem("vuex-orders", JSON.stringify(list));
  },
  // 新增删除mutation
  DELETE_ORDER(state, orderId) {
    state.orderList = state.orderList.filter(
      (order) => order.order_id !== orderId
    );
    localStorage.setItem("vuex-orders", JSON.stringify(state.orderList));
  },
  ADD_ORDER(state, order) {
    state.orderList.push(order);
    localStorage.setItem("vuex-orders", JSON.stringify(state.orderList));
  },
};

const actions = {
  async getOrderList({ commit }) {
    const localData = localStorage.getItem("vuex-orders");
    if (localData) {
      commit("SET_ORDER_LIST", JSON.parse(localData)); // 优先读取本地数据
      return;
    }
    const response = await getOrder();
    commit("SET_ORDER_LIST", response.data);
  },
  // 新增删除action
  deleteOrder({ commit, state }, orderId) {
    commit("DELETE_ORDER", orderId);
    // 强制同步本地存储
    localStorage.setItem("vuex-orders", JSON.stringify(state.orderList));
  },
  addOrder({ commit }, order) {
    commit("ADD_ORDER", order);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
